//
//  DBService.m
//  TShield
//
//  Created by Razeen on 11/25/15.
//  Copyright © 2015 lollipop. All rights reserved.
//

#import "DBService.h"

@implementation DBService


+ (id)shareDB{
    
    return [[DBService alloc]init];
}


//
- (id)init{
    
    if (self = [super init]) {
        
        NSFileManager *manager = [NSFileManager defaultManager];
        
        NSString *sandBoxPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/userData.db"];
        
        NSString *dataBasePath = [[NSBundle mainBundle]pathForResource:@"userData" ofType:@"db"];
        
//        NSLog(@"------%@--------%@",dataBasePath,sandBoxPath);
        
        if (![manager fileExistsAtPath:sandBoxPath]) {
            
            NSError *error = nil;
            
            [manager copyItemAtPath:dataBasePath toPath:sandBoxPath error:&error];
            
        }
        
        if (!_dataBase) {
            
            
            _dataBase = [[FMDatabase alloc]initWithPath:sandBoxPath];
            
            [_dataBase setShouldCacheStatements:YES];
            
        }
        
        _userModel = [[UserModel alloc]init];
    }
    
    return self;
}

//insert
- (BOOL)addAccountWithModel:(UserModel *)userInfo{
    
    BOOL isSuccess = NO;
    
    [_dataBase open];
    
    [_dataBase beginTransaction];
    
    BOOL isRollBack = NO ;
    
    @try {
        
        NSString *sql = [NSString stringWithFormat:@"insert into user (name, account, key) values ('%@','%@','%@')",userInfo.appName,userInfo.userAccount,userInfo.userkey];
        
        BOOL insertSuccess = [_dataBase executeUpdate:sql];
        
        if (insertSuccess) {
            
            isSuccess = YES;
            
        }
    }
    @catch (NSException *exception) {
        
        isRollBack = YES;
        
        [_dataBase rollback];
        
    }
    @finally {
        
        if (!isRollBack) {
            
            [_dataBase commit];
        }
    }
    
    [_dataBase close];
    
    return isSuccess;
}


//delete
- (BOOL)removeAccountWithID:(int)accountID{
    
    BOOL isSuccess = NO ;
    
    [_dataBase open];
    
    [_dataBase beginTransaction];
    
    BOOL isRollBack = NO;
    
    @try {
        
        NSString *sql = [NSString stringWithFormat:@"delete from user where id = %d",accountID];
        
        BOOL deleteSuccess = [_dataBase executeUpdate:sql];
        
        if (deleteSuccess) {
            
            isSuccess = YES ;
        }
    }
    @catch (NSException *exception) {
        
        isRollBack = YES;
        
        [_dataBase rollback];
        
    }
    @finally {
        
        if (!isRollBack) {
            
            [_dataBase commit];
        }
    }
    
    [_dataBase close];
    
    return isSuccess;
}

//change value
//search

- (NSArray *)queryAccount{
    
    NSMutableArray *accountArray = [[NSMutableArray alloc]initWithCapacity:0];
    
    [_dataBase open];
    
    NSString *sql = [NSString stringWithFormat:@"select * from user"];
    
    FMResultSet *resultSet = [_dataBase executeQuery:sql];
    
    while ([resultSet next]) {
        
        UserModel *model = [[UserModel alloc]init];
        
        model.userID = [resultSet intForColumn:@"id"];
        model.userAccount = [resultSet stringForColumn:@"account"];
        model.userkey = [resultSet stringForColumn:@"key"];
        model.appName = [resultSet stringForColumn:@"name"];
        
        [accountArray addObject:model];
    }
    
    [_dataBase close];
    
    return accountArray;
}

//jude if empty
- (BOOL)isAccountEmpty{
    
    NSArray *array = [NSArray arrayWithArray:[self queryAccount]];
    
    if (array.count > 0) {
        
        return NO;
        
    }else{
        
        return YES;
    }
}

//jude  if exist in db    判断数据库中是否存在这个key 存在返回YEs 不存在返回no
- (BOOL)isExistThisKeyInSqlite:(NSString *)key{
    
    NSArray *userArray = [self queryAccount];
    
    for (UserModel *model in userArray) {
        
        if ([model.userkey isEqualToString:key]) {
            
            return YES;
        }
    }
    return NO;
}

//jude  if exist in db    判断数据库中是否存在这个ID 存在返回YEs 不存在返回no
- (BOOL)isExistThisIDInSqlite:(int)ID{
    
    NSArray *userArray = [self queryAccount];
    
    for (UserModel *model in userArray) {
        
        if (model.userID == ID) {
            
            return YES;
        }
    }
    return NO;
}





- (void)writeToFile:(NSURL *)path{
    
    NSString *sandBoxPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/userData.db"];

    NSURL *sandURL = [NSURL fileURLWithPath:sandBoxPath];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSError *error;
    
    [manager removeItemAtURL:sandURL  error:&error];
    
    [manager copyItemAtURL:path toURL:sandURL error:&error];
    
}

- (void)deleteAllFile{
    
    NSError *error;

    NSString *sandBoxPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/userData.db"];

    NSURL *sandURL = [NSURL fileURLWithPath:sandBoxPath];

    NSFileManager *manager = [NSFileManager defaultManager];

    [manager removeItemAtURL:sandURL  error:&error];

}

- (BOOL)saveNotModelArrayintoDB:(NSArray *)array{
    
    for (NSDictionary *dic in array) {
    
        int userId = [dic[@"id"]intValue];
        
        if (![self isExistThisIDInSqlite:userId]) {
            
            UserModel *model = [[UserModel alloc]init];
            
            model.userID = userId;
            model.appName = dic[@"appName"];
            model.userAccount = dic[@"account"];
            model.userkey = dic[@"key"];
            
            return [self addAccountWithModel:model];
            
        }
    }
    
    return YES;
}




@end
